package mao.leetcode.offer;

import mao.utils.TreeNode;

/**
 * @author Totoro
 * @date 2020/8/12
 * @explain:  检测深度与判断子树是否平衡一起做了。
 */
    public class interview55_2 {

        static class Solution {
            static boolean balance;

            public boolean isBalanced(TreeNode root) {
                balance = true;
                maxDepth(root);
                return balance;
            }

            public int maxDepth(TreeNode root) {
                if (null == root || !balance) return 0;

                int leftD = maxDepth(root.left);
                int rightD = maxDepth(root.right);

                if (Math.abs(leftD - rightD) > 1) {
                    balance = false;
                    return 0;
                }

                return Math.max(leftD, rightD) + 1;
            }
        }
}
